/*
 * Copyright (c) 2022.版权所有高金磊
 */

package 领扣算法.A简单题.K次取反后最大化的数组和;

import java.util.Arrays;

public class Main {
    public static void main(String arg[]) {//main--来自高金磊

        new Main().largestSumAfterKNegations(new int[]{-8,3,-5,-3,-5,-2}, 6);
    }

    public int largestSumAfterKNegations(int[] nums, int k) {
        Arrays.sort(nums);
        int small=Integer.MAX_VALUE;
        int index=0;
        for (int i = 0; i < nums.length; i++) {
            if (nums[i]<0){
                if (k-->0){
                    nums[i]=-nums[i];
                }
            }
                if (small>Math.abs(nums[i])){
                    small=Math.abs(nums[i]);
                    index=i;
                }
        }
        int sum=Arrays.stream(nums).sum();
        if (k>0&&k%2!=0){
            return sum-nums[index]-nums[index];
        }else
            return sum;
    }
}
